<template>
  <div class="app-container">
    <com_header />
    <main>
      <div class="left">
        <img
          v-if="gameData.images[0].popup"
          :src="gameData.images[0].popup"
          alt=""
        />
        <!-- 荧光背景 -->
        <div class="bgc">
          <div
            class="light"
            :style="{
              backgroundColor: getRandomColor(Math.floor(Math.random() * 10)),
            }"
          ></div>
        </div>
      </div>
      <div class="right">
        <p class="name">{{ gameData.name }}</p>
        <p v-if="gameData.skus" class="price">
          {{ gameData.skus[0].price_format }}
        </p>
        <el-form-item label="Quantity" label-position="top">
          <el-input v-model="gameInfoForm.quantity" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            :disabled="
              gameInfoForm.quantity && gameInfoForm.quantity > 0 ? false : true
            "
            @click="openPropsItem"
            >Proceed To Payment</el-button
          >
        </el-form-item>
        <el-collapse v-model="activeNames">
          <el-collapse-item title="Prop information" name="1">
            <p v-html="gameData.description" class="description"></p>
          </el-collapse-item>
        </el-collapse>
      </div>
    </main>
    <com_footer />
    <!-- 支付弹窗 -->
    <el-dialog
      v-if="propsDetails.images[0].popup"
      v-model="pay_visible"
      lock-scroll
      style="width: 600px"
      :before-close="handleClose"
    >
      <div class="props-info">
        <img :src="propsDetails.images[0].popup" alt="" />
        <div v-if="checkoutInfo.length" class="text">
          <p class="sub_total">
            Subtotal <span>{{ checkoutInfo[0].amount_format }}</span>
          </p>
          <!-- 运费 -->
          <!-- <p class="cost">
            Shipping Cost<span>{{ checkoutInfo[1].amount_format }}</span>
          </p> -->
          <p class="cost">
            Customer Discount <span>{{ checkoutInfo[2].amount_format }}</span>
          </p>
          <p class="total">
            Total <span>{{ checkoutInfo[3].amount_format }}</span>
          </p>
        </div>
      </div>

      <el-form
        ref="paypalFormRef"
        :model="paypalForm"
        :rules="paypalRules"
        label-width="auto"
        label-position="top"
        status-icon
        autocomplete="off"
        hide-required-asterisk
        class="credit-form"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <p class="title">delivery Infomation</p>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="gameId">
              <el-input
                v-model="paypalForm.gameId"
                placeholder="Battle TAG/Battle Email"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="gameName">
              <el-input
                v-model="paypalForm.gameName"
                placeholder="Character Name"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <p class="title">Personal Information</p>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="firstName">
              <el-input
                v-model="paypalForm.firstName"
                placeholder="First Name"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="lastName">
              <el-input v-model="paypalForm.lastName" placeholder="Last Name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="gameEmail">
              <el-input v-model="paypalForm.gameEmail" placeholder="Email" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="telephone">
              <el-input
                v-model="paypalForm.telephone"
                placeholder="Telephone"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <p class="title">Payment Methods</p>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="methods">
              <el-select v-model="pay_kind">
                <el-option label="PayPal" value="1" />
                <el-option label="Credit Card" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- paypal 支付 -->
          <el-col v-if="pay_kind == 1" :span="24">
            <el-form-item prop="email">
              <el-input
                v-model="paypalForm.email"
                placeholder="example@email.com"
              />
            </el-form-item>
          </el-col>
          <!-- 信用卡 支付 -->
          <el-col v-if="pay_kind == 2" :span="24">
            <el-form-item prop="CARDNO">
              <el-input v-model="paypalForm.CARDNO" placeholder="Card Number" />
            </el-form-item>
          </el-col>
          <el-col v-if="pay_kind == 2" :span="12">
            <el-form-item prop="ExpiryData">
              <el-date-picker
                v-model="paypalForm.ExpiryData"
                type="month"
                placeholder="MM/YY"
                format="MM/YY"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="pay_kind == 2" :span="12">
            <el-form-item prop="CVV">
              <el-input
                v-model="paypalForm.CVV"
                placeholder="Security code"
                :suffix-icon="Postcard"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="pay_kind == 2" :span="24">
            <el-form-item prop="CARDHolderName">
              <el-input
                v-model="paypalForm.CARDHolderName"
                placeholder="Cardholder name"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <el-button @click="handlePaypal(paypalFormRef)"
                >Pay Now</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="pay-info">
        <p class="title">Payment Methods</p>
        <p class="text">We accept the following secure payment methods</p>
        <div class="icons">
          <img src="@/assets/pay/3.png" alt="" />
          <img src="@/assets/pay/2.png" alt="" />
          <img src="@/assets/pay/4.png" alt="" />
          <img src="@/assets/pay/1.png" alt="" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import com_header from "@/components/com_header/index.vue";
import com_footer from "@/components/com_footer/index.vue";

import { productDetails } from "@/api/product";
import { carts, addCart, deleteAll } from "@/api/cart";
import { show, paypal } from "@/api/order";
import { confirm, checkoutList } from "@/api/checkout";
import { ref, reactive, nextTick, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";

const route = useRoute();
const router = useRouter();
const store = useStore();

// 初始化 清空购物车
const deleteAllCart = async () => {
  await deleteAll();
};
deleteAllCart();

// 获取游戏详情
const activeNames = ref(["1"]);
const gameData = ref({
  meta_description: "",
  images: [{ popup: "" }],
});
const getGameData = () => {
  productDetails(route.query.id).then((res) => {
    gameData.value = res.data.product;
    // console.log(gameData.value);
  });
};
// getGameData();

// 表单配置
const gameInfoForm = reactive({
  quantity: 1,
});

// 打开支付窗口
const pay_visible = ref(false);
const pay_kind = ref("1");
const propsDetails = ref({
  images: [{ popup: "" }],
  skus: [{ price_format: "" }],
});
const openPropsItem = () => {
  if (!store.state.userInfo.access_token) {
    ElMessage({
      message: "Please Login First!",
      type: "warning",
    });
  } else {
    productDetails(route.query.id).then((res) => {
      propsDetails.value = { ...res.data.product };
      // console.log(propsDetails.value);
      // 加车
      addCart({
        sku_id: propsDetails.value.skus[0].id,
        quantity: gameInfoForm.quantity,
      }).then(() => {
        pay_visible.value = true;
        getCheckoutList();
      });
    });
  }
};

// 获取checkout 信息
const checkoutInfo = ref({});
const getCheckoutList = () => {
  checkoutList().then((res) => {
    checkoutInfo.value = res.data.totals;
    // console.log(checkoutInfo.value);
  });
};

// paypal配置
const paypalFormRef = ref(null);
const paypalForm = reactive({
  email: "", // hdgsrichelle@yahoo.com
  username: "", // 网站昵称或者网站邮箱
  amount: "",
  ip: "127.0.0.1",
  customer: "stellar-game",

  // 虚拟的参数
  gameId: "",
  gameName: "",
  firstName: "",
  lastName: "",
  gameEmail: "",
  telephone: "",

  // 信用卡信息
  CARDNO: "", // 4514617650488994
  ExpiryData: "",
  CVV: "",
  CARDHolderName: "",
});
const paypalRules = reactive({
  // paypal 校验
  email: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "the format is incorrect!",
      trigger: "blur",
    },
  ],
  // 虚拟游戏信息 校验
  gameId: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
  gameName: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
  firstName: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
  lastName: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
  gameEmail: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "the format is incorrect!",
      trigger: "blur",
    },
  ],
  telephone: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
  // 信用卡校验
  CARDNO: [
    {
      pattern:
        /^(?:4[0-9]{12}(?:[0-9]{3})?)$/ ||
        /^(?:5[1-5][0-9]{14})$/ ||
        /^(?:3[47][0-9]{13})$/ ||
        /^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/,
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
  CVV: [
    { min: 3, max: 3, message: "Length should be 3", trigger: "blur" },
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
  ExpiryData: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
  CARDHolderName: [
    {
      required: true,
      message: "Required!",
      trigger: "blur",
    },
  ],
});

// paypal支付
const handlePaypal = async (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      // 下单
      confirm({
        website: "stellar-game",
      }).then((res) => {
        // 获取订单详情
        show(res.data.number).then((res) => {
          paypalForm.username = res.data.email;
          paypalForm.amount = res.data.total_format;
          console.log("订单号:", res.data.number);

          // paypal 支付
          if (pay_kind.value == 1) {
            paypal(res.data.number, { ...paypalForm })
              .then((res) => {
                // console.log("paypal支付链接:", res.data.paylink);
                ElMessageBox.confirm(
                  "You are about to jump to a new page to make the payment!",
                  {
                    confirmButtonText: "sure",
                    cancelButtonText: "cancel",
                    customClass: "messageBox",
                    type: "",
                    showClose: false,
                  }
                )
                  .then(() => {
                    if (res.data.paylink) {
                      window.open(res.data.paylink);
                      pay_visible.value = false;
                    }
                  })
                  .catch(() => {});
              })
              .catch((res) => {
                ElMessage({
                  message: "Failed to pay !",
                  type: "error",
                });
                pay_visible.value = false;
              });
          } else {
            // 信用卡支付
            pay_visible.value = false;
            ElMessage.error("Payment failed!");
            return;
          }
        });
      });
    } else {
      return false;
    }
  });
};

// 关闭支付弹窗
const handleClose = () => {
  deleteAllCart(); // 清空购物车

  gameInfoForm.quantity = 1;

  paypalForm.email = "";
  paypalForm.username = "";
  paypalForm.amount = "";

  propsDetails.value = {
    images: [{ popup: "" }],
    skus: [{ price_format: "" }],
  };

  pay_visible.value = false;
};

// 方法: 获取图片背景荧光色
const getRandomColor = (index) => {
  const colorList = [
    "rgba(136, 71, 255, 0.3)",
    "rgba(255, 255, 255, 0.3)",
    "rgba(255, 206, 97, 0.3)",
    "rgba(203, 56, 55, 0.3)",
  ];
  return ` ${colorList[index % 4]}`;
};

watch(
  () => route.query.id,
  (n) => {
    if (n) {
      getGameData();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
</script>

<style lang="scss" scoped>
.app-container {
  padding-top: 80px;
  width: 100%;
  min-height: 100vh;
  // background: #1d1d24;
  background: #181f2c;
  main {
    margin: 60px auto 0;
    width: 1400px;
    min-height: 700px;
    display: flex;
    gap: 0 100px;
    .left {
      width: 180px;
      height: 180px;
      position: relative;
      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
      .bgc {
        display: flex;
        position: absolute;
        inset: 0px;
        -webkit-box-align: center;
        align-items: center;
        -webkit-box-pack: center;
        justify-content: center;
        .light {
          width: 70%;
          height: 70%;
          position: absolute;
          border-radius: 50%;
          filter: blur(40px);
          z-index: 1;
        }
      }
    }
    .right {
      flex: 1;
      .name {
        margin-bottom: 30px;
        font-size: 30px;
        color: #fff;
      }
      .price {
        margin-bottom: 30px;
        font-size: 30px;
        font-weight: 700;
        color: #15a251;
      }
      ::v-deep .el-form-item {
        .el-form-item__label {
          font-size: 20px;
          color: #fff;
          background: #1d1d24;
        }
        .el-input {
          width: 300px;
          background: #1d1d24;
          .el-input__wrapper {
            border: none;
            border: 1px solid #616363;
            box-shadow: none;
            background: #1d1d24;
            .el-input__inner {
              border: none;
              background: #1d1d24;
              color: #fff;
            }
          }
        }
        .el-button {
          width: 300px;
          height: 60px;
          color: #fff;
          background: #15a251;
          border: none;
          &:hover {
            background: #25b564;
          }
        }
      }
      ::v-deep .el-collapse {
        width: 100%;
        border: none;
        .el-collapse-item {
          border: none;
          .el-collapse-item__header {
            margin-bottom: 20px;
            font-size: 20px;
            color: #fff;
            background: #1d1d24;
            border: none;
          }
          .el-collapse-item__content {
            background: rgb(29, 29, 36);
          }
        }
      }
    }
  }
  ::v-deep .el-dialog {
    background: rgb(36, 36, 46);
    .el-dialog__header {
      position: absolute;
      top: 0px;
      right: -80px;
      .el-dialog__headerbtn {
        padding: 10px;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        .el-icon {
          font-size: 20px;
          color: #fff;
        }
        &:hover {
          background: #444;
        }
      }
    }
    .el-dialog__body {
      padding: 10px;
      .props-info {
        margin-bottom: 20px;
        display: flex;
        justify-content: space-between;
        img {
          margin-right: 20px;
          width: 80px;
          height: 80px;
          border-radius: 4px;
          object-fit: contain;
        }
        .text {
          margin-right: 40px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: end;
          color: #9ba2a2;
          p {
            margin-bottom: 4px;
            font-size: 13px;
            span {
              margin-left: 14px;
              display: inline-block;
            }
          }
          .total {
            margin-top: 10px;
            font-size: 26px;
            font-weight: 700;
            color: #15a251;
            span {
              margin-left: 10px;
              display: inline-block;
              color: #15a251;
            }
          }
        }
      }
      .gameInfo-box {
        .el-form {
          margin-bottom: 10px;
          .title {
            margin-bottom: 10px;
            font-size: 18px;
            color: #b4b7b7;
          }
        }
      }
      .credit-form {
        padding: 20px;
        margin-bottom: 20px;
        border-radius: 4px;
        border: 2px solid #525050;
        .title {
          margin-bottom: 10px;
          font-size: 18px;
          color: #b4b7b7;
        }
        .el-select {
          width: 200px;
          .el-select__wrapper {
            box-shadow: none !important;
            .el-select__selected-item {
              color: #333;
              box-shadow: none !important;
            }
          }
        }
        .el-input {
          --el-input-hover-border: none !important;
          --el-input-text-color: none !important;
          --el-input-focus-border: none !important;
          --el-input-focus-border-color: none !important;
          box-shadow: none !important;
          .el-input__wrapper {
            border: 1px solid #000;
            box-shadow: none !important;
            --el-input-hover-border: none !important;
            --el-input-text-color: none !important;
            --el-input-focus-border: none !important;
            --el-input-focus-border-color: none !important;
            .el-input__inner {
              color: #333;
            }
          }
        }
        .el-button {
          width: 200px;
          height: 40px;
          color: #fff;
          background: #15a251;
          border: none;
          &:hover {
            background: #25b564;
          }
        }
      }
      .pay-info {
        margin-top: 10px;
        display: flex;
        flex-direction: column;
        align-items: end;
        .title {
          margin-bottom: 10px;
          font-size: 16px;
          color: #b4b7b7;
        }
        .text {
          margin-bottom: 16px;
          font-size: 16px;
          color: #b4b7b7;
        }
        .icons {
          img {
            padding: 4px;
            margin-right: 10px;
            width: 60px;
            height: 30px;
            object-fit: contain;
            border: 1px solid #b4b7b7;
            border-radius: 4px;
            background: #fff;
          }
        }
      }
    }
  }
}
</style>